//设置html根目录字体大小
require(['jquery', '../modules/pageSize', '../modules/popup'], function ($, pageSetSize, popup) {
    setRootFontSize(pageSetSize);
    var maxBackPrice = $("#max-back-price").val();
    var curBackPrice = "0";
    var cost_freight = "0.00";
    var isPop = false;
    $(".btn-refund-tps").bind('click', function () {
        popup.popup('.member-refund-tips');
        if (isPop) return;
        isPop = true;
        $('.member-refund-tips .confirm').click(function (e) {
            var items = "";

            $('.dataItem .choice-btn').each(function () {
                var cparent = $(this).parents(".dataItem");
                if ($(this).hasClass("active")) {
                    items += (items == "" ? "" : ",") + cparent.attr("data-id") + "#" + cparent.find(".goods_number").val();
                }
            });
            var data = {
                'order_id': $("#order_id").val(),
                'price': $("#price").val(),
                'item_id': items,
                'message': $("#refundReason").val(),
                'comment': $("#refundComment").val(),
                'phone': $("#telephone").val(),
                'image': $("#upload_image").val(),
                'cost_freight': cost_freight
            };
            $.ajax({
                type: "post",
                url: "/Home/MemberRefundReturn/ajax_refund"+getFixedExtraUrl(),
                data: data,
                dataType: "json",
                success: function (data) {
                    if (data.flag) {
                        popup.alertPopup('申请成功！');
                    } else {
                        popup.alertPopup('申请失败！');
                    }
                },
                error: function () {
                    popup.alertPopup('服务器异常，请稍后重试！');
                }
            });
            window.location.reload();
        })
    });
    $('.choice-btn').on("click", function () {
        var itemObj = $(this).parents(".dataItem");        
        if(itemObj.hasClass('dataItem')){
            var price = itemObj.attr("data-price");
            var num = itemObj.find(".goods_number").val();
            var cpstr = "";
            if($(this).hasClass('active')){
                cpstr = getFixedFloat(price.toString(), num.toString(), "*");
                curBackPrice = getFixedFloat(curBackPrice.toString(), cpstr, "-");
                $("#price").val(curBackPrice);
                $(this).removeClass('active');
            }else{
                cpstr = getFixedFloat(price.toString(), num.toString(), "*");
                curBackPrice = getFixedFloat(curBackPrice.toString(), cpstr, "+");
                $("#price").val(curBackPrice);           
                $(this).addClass('active');
            }
        }else{
            // 运费
            if($(this).hasClass('active')){                
                curBackPrice = getFixedFloat(curBackPrice.toString(), $("#freight").attr("data-fee"), "-");
                cost_freight = "0.00";
                $("#price").val(curBackPrice);
                $(this).removeClass('active');
            }else{
                curBackPrice = getFixedFloat(curBackPrice.toString(), $("#freight").attr("data-fee"), "+");
                cost_freight = $("#freight").attr("data-fee");
                $("#price").val(curBackPrice);
                $(this).addClass('active');
            }
        }
    });
    $("#price").on("keyup", function () {
        if($(this).val() == ""){
            $(this).val("0.00");
        }else{
            if(!isNaN($(this).val())){
                var cbprice = parseFloat($(this).val());
                if (cbprice < 0) {
                    $(this).val(0);
                } else if (cbprice > maxBackPrice) {
                    $(this).val(maxBackPrice);
                }
            }else{
                $(this).val("0.00");
            }
        }
    });

    $(".change-number a").on("click", function () {
        var gnumObj = $(this).parent().children(".goods_number");
        var num = parseInt(gnumObj.val());
        var realnum = parseInt($(this).parents(".dataItem").attr("data-num"));
        if ($(this).hasClass("plus")) {
            if (num < realnum) {
                gnumObj.val(++num);
            }
        } else {
            if (num > 1) {
                gnumObj.val(--num);
            }
        }
    });
    $(".change-number .goods_number").on("blur", function () {
        var realnum = parseInt($(this).parents(".dataItem").attr("data-num"));
        if (/\d+/.test($(this).val())) {
            if (parseInt($(this).val()) > realnum) {
                $(this).val(realnum);
            }
        } else {
            $(this).val(0);
        }
    });
});
//选择退款原因
require(['jquery'], function ($) {
    var _self = document.getElementById('refundReason');

    function popupReasonSelect(e) {
        e.preventDefault();
        var _self = this;
        _self.refund = document.createElement("div");
        _self.refund.className = "refundSelect";
        _self.refund.innerHTML = '<div class="area_ctrl slideInUp">' +
            '<div class="area_btn_box">' +
            '<div class="area_btn refund_cancel">取消</div>' +
            '<div class="area_btn refund_finish">确定</div>' +
            '</div>' +
            '<div class="area_roll_mask">' +
            '<div class="area_roll">' +
            '<div>' +
            '<div class="gear refund_reason">' +
            '<div class="tooth">卖家发错货</div>' +
            '<div class="tooth">商品变质/发霉/有异物</div>' +
            '<div class="tooth">成分与商品描述不符</div>' +
            '<div class="tooth">包装/商品破损</div>' +
			'<div class="tooth">拍错了/不喜欢</div>' +
			'<div class="tooth">七天无条件</div>' +
			'<div class="tooth">其他</div>' +
            '</div>' +
            '<div class="area_grid"></div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        document.body.appendChild(_self.refund);
        var refund_cancel = _self.refund.querySelector(".refund_cancel");
        refund_cancel.addEventListener('touchstart', function (e) {
            close(e);
        });
        var refund_finish = _self.refund.querySelector(".refund_finish");
        refund_finish.addEventListener('touchstart', function (e) {
            finish(e);
        });
        var refund_reason = _self.refund.querySelector(".refund_reason");
        refund_reason.addEventListener('touchstart', gearTouchStart);
        refund_reason.addEventListener('touchmove', gearTouchMove);
        refund_reason.addEventListener('touchend', gearTouchEnd);


    }

    //触摸开始
    function gearTouchStart(e) {
        e.preventDefault();
        var target = e.target;
        while (true) {
            if (!target.classList.contains("gear")) {
                target = target.parentElement;
            } else {
                break
            }
        }
        clearInterval(target["int_" + target.id]);
        target["old_" + target.id] = e.targetTouches[0].screenY;
        target["o_t_" + target.id] = (new Date()).getTime();
        var top = target.getAttribute('top');
        if (top) {
            target["o_d_" + target.id] = parseFloat(top.replace(/em/g, ""));
        } else {
            target["o_d_" + target.id] = 0;
        }
        target.style.webkitTransitionDuration = target.style.transitionDuration = '0ms';
    }

    //手指移动
    function gearTouchMove(e) {
        e.preventDefault();
        var target = e.target;
        while (true) {
            if (!target.classList.contains("gear")) {
                target = target.parentElement;
            } else {
                break
            }
        }
        target["new_" + target.id] = e.targetTouches[0].screenY;
        target["n_t_" + target.id] = (new Date()).getTime();
        var f = (target["new_" + target.id] - target["old_" + target.id]) * 30 / window.innerHeight;
        target["pos_" + target.id] = target["o_d_" + target.id] + f;
        target.style["-webkit-transform"] = 'translate3d(0,' + target["pos_" + target.id] + 'em,0)';
        target.setAttribute('top', target["pos_" + target.id] + 'em');
        if (e.targetTouches[0].screenY < 1) {
            gearTouchEnd(e);
        }
        ;
    }

    //离开屏幕
    function gearTouchEnd(e) {
        e.preventDefault();
        var target = e.target;
        while (true) {
            if (!target.classList.contains("gear")) {
                target = target.parentElement;
            } else {
                break;
            }
        }
        var flag = (target["new_" + target.id] - target["old_" + target.id]) / (target["n_t_" + target.id] - target["o_t_" + target.id]);
        if (Math.abs(flag) <= 0.2) {
            target["spd_" + target.id] = (flag < 0 ? -0.08 : 0.08);
        } else {
            if (Math.abs(flag) <= 0.5) {
                target["spd_" + target.id] = (flag < 0 ? -0.16 : 0.16);
            } else {
                target["spd_" + target.id] = flag / 2;
            }
        }
        if (!target["pos_" + target.id]) {
            target["pos_" + target.id] = 0;
        }
        rollGear(target);
    }

    //缓动效果
    function rollGear(target) {
        var d = 0;
        var stopGear = false;

        function setDuration() {
            target.style.webkitTransitionDuration = target.style.transitionDuration = '200ms';
            stopGear = true;
        }

        clearInterval(target["int_" + target.id]);
        target["int_" + target.id] = setInterval(function () {
            var pos = target["pos_" + target.id];
            var speed = target["spd_" + target.id] * Math.exp(-0.03 * d);
            pos += speed;
            if (Math.abs(speed) > 0.1) {
            } else {
                var b = Math.round(pos / 2) * 2;
                pos = b;
                setDuration();
            }
            if (pos > 0) {
                pos = 0;
                setDuration();
            }
			if (pos < -12.5) {
                pos = -12;
                setDuration();
            }
            var minTop = -(target.dataset.len - 1) * 2;
            if (pos < minTop) {
                pos = minTop;
                setDuration();
            }
            if (stopGear) {
                var gearVal = Math.abs(pos) / 2;
                setGear(target, gearVal);
                clearInterval(target["int_" + target.id]);
            }
            target["pos_" + target.id] = pos;
            target.style["-webkit-transform"] = 'translate3d(0,' + pos + 'em,0)';
            target.setAttribute('top', pos + 'em');
            d++;
        }, 30);
    }

    //控制插件滚动后停留的值
    function setGear(target, val) {
        val = Math.round(val);
        target.setAttribute("val", val);
    }

    //重置节点个数
    function setGearTooth(data) {
        var _self = this;
        var item = data || [];
        var l = item.length;
        var gearChild = _self.gearArea.querySelectorAll(".gear");
        var gearVal = gearChild[_self.index].getAttribute('val');
        var maxVal = l - 1;
        if (gearVal > maxVal) {
            gearVal = maxVal;
        }
        gearChild[_self.index].setAttribute('data-len', l);
        if (l > 0) {
            var id = item[gearVal][this.keys['id']];
            var childData;
            switch (_self.type) {
                case 1:
                    childData = item[gearVal].child
                    break;
                case 2:
                    var nextData = _self.data[_self.index + 1]
                    for (var i in nextData) {
                        if (i == id) {
                            childData = nextData[i];
                            break;
                        }
                    }
                    ;
                    break;
            }
            var itemStr = "";
            for (var i = 0; i < l; i++) {
                itemStr += "<div class='tooth'  ref='" + item[i][this.keys['id']] + "'>" + item[i][this.keys['name']] + "</div>";
            }
            gearChild[_self.index].innerHTML = itemStr;
            gearChild[_self.index].style["-webkit-transform"] = 'translate3d(0,' + (-gearVal * 2) + 'em,0)';
            gearChild[_self.index].setAttribute('top', -gearVal * 2 + 'em');
            gearChild[_self.index].setAttribute('val', gearVal);
            _self.index++;
            if (_self.index > 2) {
                _self.index = 0;
                return;
            }
            _self.setGearTooth(childData);
        } else {
            gearChild[_self.index].innerHTML = "<div class='tooth'></div>";
            gearChild[_self.index].setAttribute('val', 0);
            if (_self.index == 1) {
                gearChild[2].innerHTML = "<div class='tooth'></div>";
                gearChild[2].setAttribute('val', 0);
            }
            _self.index = 0;
        }
    }

    function finish(e) {
        var refund_reason = _self.refund.querySelector(".refund_reason");
        var provinceVal = parseInt(refund_reason.getAttribute("val"));
        if(isNaN(provinceVal)){
            provinceVal = 0;
        }
        var provinceText = refund_reason.childNodes[provinceVal].textContent;
        var provinceCode = refund_reason.childNodes[provinceVal].getAttribute('ref');
        _self.value = provinceText;
        if (this.valueTo) {
            this.valueTo.value = provinceCode;
        }
        close(e);
    }
    // 关闭插件
    function close(e) {
        e.preventDefault();
        document.body.removeChild(_self.refund);
        _self.refund = null;
    }
    _self.addEventListener('touchstart', popupReasonSelect);
});